/**
 * Copyright (C) 2009 aileron.cc
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cc.aileron.orm.factory.serial;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import cc.aileron.accessor.PojoAccessorFactory;

import com.google.inject.Inject;
import com.google.inject.Singleton;

/**
 * statement.getGeneratedKeys() を使用したナンバの取得実装
 * 
 * @author Aileron
 * 
 */
@Singleton
public class G2DaoSerialGeneratedKeys implements G2DaoSerial
{
    /*
     * (非 Javadoc)
     * 
     * @see
     * cc.aileron.dao.db.method.serial.DbExecuteSerial#getSerialNumber(java.
     * sql.PreparedStatement, java.lang.String, java.lang.Object)
     */
    public void getSerialNumber(final PreparedStatement statement,
            final String name,
            final Object parameter) throws SQLException
    {
        final ResultSet rs = statement.getGeneratedKeys();
        final ResultSetMetaData meta = rs.getMetaData();
        if (meta.getColumnCount() > 0)
        {
            if (rs.next())
            {
                final int value = rs.getInt(1);
                factory.create(parameter)
                    .set(name, value);
            }
        }
        rs.close();
    }

    /**
     * contractor injection
     * 
     * @param factory
     */
    @Inject
    public G2DaoSerialGeneratedKeys(final PojoAccessorFactory factory)
    {
        this.factory = factory;
    }

    /**
     * factory
     */
    private final PojoAccessorFactory factory;
}